package com.cameron.serviceedu.controller;

import com.cameron.entity.BackendLoginVo;
import com.cameron.entity.BackendMemberDto;
import com.cameron.serviceedu.client.UserCenterClient;
import com.cameron.utils.JwtUtils;
import com.cameron.utils.Result;
import com.hooper.util.RandomUtil;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

import static com.cameron.constant.RoleConstant.MEMBER_ADMIN;

/**
 * 模拟登录数据
 *
 * @author cameron
 */
@RestController
@RequestMapping("/service/user")
@Api("模拟数据")
@CrossOrigin
@Slf4j
public class BackendUserController {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private UserCenterClient userCenterClient;


    @PostMapping("login")
    public Result login(@RequestBody BackendLoginVo loginVo, HttpServletRequest request) {
        BackendMemberDto memberDto = userCenterClient.backendLogin(loginVo);
        String token = JwtUtils.getJwtToken(memberDto.getId(), memberDto.getName(), memberDto.getRoles());
        stringRedisTemplate.opsForValue().set("token", token, 10, TimeUnit.HOURS);
        return Result.ok().data("token", token);
    }

    @GetMapping("info")
    public Result info(String token) {
        BackendMemberDto memberDto = JwtUtils.getLoginMemberByToken(token);
        if (ObjectUtils.isEmpty(memberDto)) {
            return Result.error().message("token为空!");
        }
        return Result.ok().data("roles", memberDto.getRoles() == MEMBER_ADMIN ? "admin" : "teacher")
                .data("name", memberDto.getName())
                .data("avatar", "https://cam-guliedu.oss-cn-beijing.aliyuncs.com/radom-avatar/avatar/" + RandomUtil.randomInt(1, 100) + ".png");
    }

    @PostMapping("logout")
    public Result logout(String token) {
        log.info("退出用户-->token:{}", token);
        return Result.ok();
    }
}
